<template>
  <div class="BlogComment-container">
    <MessageArea
      title="评论列表"
      :subTitle="`(${data.total})`"
      :list="data.rows"
      :isLoading="isLoading"
      @submit="submit"
    />
  </div>
</template>

<script>
import fetchData from "@/mixins/fetchData.js";
import MessageArea from "@/components/MessageArea";
import { getComment, postComment } from "@/api/blog.js";
export default {
  mixins: [fetchData({ total: 0, rows: [] })],
  components: { MessageArea },
  data: () => ({
    page: 1,
    limit: 10,
    isLoading: false,
  }),
  computed: {
    hasMore() {
      return this.data.rows.length < this.data.total;
    },
  },
  created() {
    this.$bus.$on("mainScroll", this.scroll);
  },
  destroyed() {
    this.$bus.$off("mainScroll", this.scroll);
  },
  methods: {
    async fetchData() {
      return await getComment(this.$route.params.id, this.page, this.limit);
    },
    async fetahMore() {
      if (this.hasMore) return; // 没有更多了
      this.isLoading = true;
      this.page++;
      const { total, rows } = await this.fetchData();
      this.data.rows = this.data.rows.concat(rows);
      this.data.total += total;
      this.isLoading = false;
    },
    scroll(dom) {
      const rang = 100;
      if (
        !this.isLoading &&
        dom &&
        Math.abs(dom.scrollTop + dom.clientHeight - dom.scrollHeight) <= rang
      ) {
        this.fetahMore();
      }
    },
    async submit(formData, callback) {
      console.log("formData", formData);
      const resp = await postComment({
        blogId: this.$route.params.id,
        ...formData,
      });
      this.data.rows.unshift(resp);
      this.data.total++;
      callback("提交成功！");
    },
  },
};
</script>

<style lang='less' scoped>
.BlogComment-container {
  margin: 30px 0;
}
</style>
